package com.finance.system.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.finance.base.constant.BaseConstants;
import com.finance.base.enums.CombineWeightEnum;
import com.finance.base.enums.OpearteEnum;
import com.finance.base.enums.StateEnum;
import com.finance.base.enums.TargetEnum;
import com.finance.base.exception.BaseException;
import com.finance.framework.controller.BaseController;
import com.finance.framework.controller.Result;
import com.finance.framework.file.FileUtils;
import com.finance.framework.lang.BeanUtils;
import com.finance.framework.lang.Page;
import com.finance.framework.lang.PageResultBO;
import com.finance.rule.service.ISettingLogService;
import com.finance.system.bean.pojo.Supplier;
import com.finance.system.bean.pojo.SupplierGroup;
import com.finance.system.bean.pojo.SupplierList;
import com.finance.system.bean.pojo.User;
import com.finance.system.export.SupplierImportTemplateBean;
import com.finance.system.export.SupplierParse;
import com.finance.system.request.SupplierExportReq;
import com.finance.system.request.SupplierListReq;
import com.finance.system.request.SupplierReq;
import com.finance.system.service.ISupplierService;
import com.finance.util.export.ExportBuilder;
import com.finance.util.export.ExportFactory;
import com.finance.util.export.ImportUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 供货商管理
 * Created by gly on 2017/3/31.
 */
@Controller
@RequestMapping("/system/supplier")

public class SupplierController extends BaseController {

    @Resource
    private ISupplierService supplierService;
    @Resource
    private ISettingLogService settingLogService;
    private ObjectMapper objectMapper = new ObjectMapper();

    @RequestMapping("/index")
    public String index() {
        return "system/supplier/index";
    }

    /**
     * 分页查询
     *
     * @param form
     * @return
     */
    @RequestMapping("/list")
    public Result list(SupplierListReq form) {
        Page page = Page.getInstance(form);
        SupplierList supplierList = new SupplierList();
        supplierList.setName(form.getName());
        supplierList.setCode(form.getCode());
        supplierList.setGroupName(form.getGroupName());
        supplierList.setState(form.getState());
        page.setParams(supplierList);
        PageResultBO<Supplier> pageResultBO = supplierService.listByPage(page);
        return getSuccessResult(pageResultBO);

    }

    /**
     * 查询所有供货商
     *
     * @return
     */
    @RequestMapping("/listall")
    public Result listAll() {
        List<Supplier> list = supplierService.listAll();
        return getSuccessResult(list);
    }

    /**
     * 添加新供应商
     *
     * @param supplierReq
     * @return
     * @throws BaseException
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result add(@Valid SupplierReq supplierReq) throws BaseException {
        User user = getAuthUser();
        if (user == null) {
            throw new BaseException(BaseConstants.ERR_UNKONW_USER);
        }
        Supplier supplier = new Supplier();
        supplier.setCreateUid(user.getId());
        supplier.setName(supplierReq.getName());
        supplier.setState(StateEnum.Valid.getState());
        supplier.setIsCombined(supplierReq.getIsCombined());
        supplier.setCode(supplierReq.getCode());
        if (!StringUtils.isEmpty(supplierReq.getGroupId())) {
            supplier.setGroupId(Long.parseLong(supplierReq.getGroupId()));
        } else if (!StringUtils.isEmpty(supplierReq.getGroupCode()) && !StringUtils.isEmpty(supplierReq.getGroupName())) {
            SupplierGroup supplierGroup = new SupplierGroup();
            supplierGroup.setCreateUid(user.getId());
            supplierGroup.setName(supplierReq.getGroupName());
            supplierGroup.setState(StateEnum.Valid.getState());
            supplierGroup.setCode(supplierReq.getGroupCode());
            if (!supplierService.groupCodeIsExist(supplierReq.getGroupCode())) {
                throw new BaseException(BaseConstants.ERR_SUPPLIERGROUP_CODE_EXIST);
            }
            Long id = supplierService.addGroup(supplierGroup);
            supplier.setGroupId(id);

        }
        if (!supplierService.codeIsExist(supplierReq.getCode())) {
            throw new BaseException(BaseConstants.ERR_SUPPLIER_CODE_EXIST);
        }
        this.supplierService.add(supplier);
        return getSuccessResult("添加供应商成功");

    }

    /**
     * 修改供应商信息
     *
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(String id, HttpServletRequest request) {
        Supplier supplier = supplierService.getById(Long.parseLong(id));
        request.setAttribute("supplier", supplier);
        return "system/supplier/update";
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Result update(String id, @Valid SupplierReq supplierReq) {
        if (StringUtils.isBlank(id)) {
            throw new BaseException(BaseConstants.ERR_INVALID_PARAMETER);
        }
        Supplier oldSupplier = supplierService.getById(Long.parseLong(id));
        if (oldSupplier == null) {
            throw new BaseException(BaseConstants.ERR_NON_EXISTENT);
        }
        User user = getAuthUser();
        if (user == null) {
            throw new BaseException(BaseConstants.ERR_UNKONW_USER);
        }
        Supplier supplier = new Supplier();
        supplier.setUpdateUid(user.getId());
        supplier.setId(Long.parseLong(id));
        supplier.setName(supplierReq.getName());
        supplier.setCode(supplierReq.getCode());
        supplier.setIsCombined(supplierReq.getIsCombined());
        if(StringUtils.isBlank(supplierReq.getGroupId())){
            throw  new BaseException(BaseConstants.ERR_SUPPLIER_GROUP_IS_NULL);
        }
        supplier.setGroupId(Long.parseLong(supplierReq.getGroupId()));
        supplier.setState(supplierReq.getState());
        supplierService.update(supplier);

        String oldValue = null;
        try {
            oldValue = objectMapper.writeValueAsString(oldSupplier);
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage(), e);
        }
        settingLogService.addLog(user, OpearteEnum.UPDATE, TargetEnum.SUPPLIER_INFO, oldValue);

        return getSuccessResult("修改供应商信息成功");
    }

    /**
     * 通过 ID 获取供货商对应信息
     *
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "/getbyid", method = RequestMethod.POST)
    public Result getById(String id, HttpServletRequest request) {
        return getSuccessResult(supplierService.getById(Long.parseLong(id)));
    }

    /**
     * 删除供应商信息
     *
     * @param ids
     * @return
     */
    @RequestMapping("/delete")
    public Result delete(String ids) {
        if (StringUtils.isEmpty(ids)) {
            throw new BaseException(BaseConstants.ERR_INVALID_PARAMETER);
        }
        User user = getAuthUser();
        if (user == null) {
            throw new BaseException(BaseConstants.ERR_UNKONW_USER);
        }
        List<String> list = Arrays.asList(ids.split(","));
        if (list.size() > 0) {
            boolean result = supplierService.delete(user.getId(), list);
            return getSuccessResult(result);
        }
        return getSuccessResult("删除供应商成功");
    }

    /**
     * 查询出所有供货商分组名称
     *
     * @return
     */
    @RequestMapping("/listgroups")
    public Result listGroups() {
        return getSuccessResult(supplierService.listGroups());
    }


    /**
     * 导入Excel模板下载
     */
    @RequestMapping("/exporttemplate")
    public void export(HttpServletResponse response) {
        try {
            ExportBuilder builder = new ExportBuilder
                    (SupplierImportTemplateBean.class,
                            new SupplierParse()
                    );
            ExportFactory factory = ExportFactory.getExportFactory(
                    builder);
            factory.setDataList(new ArrayList<Supplier>()).outPut(response);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);

        }
    }


    /**
     * 导入结果下载
     */
    @RequestMapping("/down")
    public void importData(String fileKey, HttpServletResponse response) {
        FileUtils.downFile(fileKey, response);
    }

    /**
     * 导入
     */
    @RequestMapping("/import")
    public Result importData(@RequestParam("file") CommonsMultipartFile[] multipartFile) {
        User user = getAuthUser();
        InputStream in = null;
        List<Supplier> errList = null;
        List<String> errMsg = null;
        int successNums = 0;
        int totalNums = 0;
        try {
            in = multipartFile[0].getInputStream();
            List<SupplierImportTemplateBean> list = ImportUtil.getImportFactory(in).outResult(SupplierImportTemplateBean.class);
            errList = new ArrayList<Supplier>();
            errMsg = new ArrayList<String>();
            if (list != null && list.size() > 0) {
                for (SupplierImportTemplateBean bean : list) {
                    SupplierExportReq form = new SupplierExportReq();
                    String groupId = "";
                    if (!StringUtils.isEmpty(bean.getGroupName())) {
                        groupId = supplierService.getGroupIdByName(bean.getGroupName());
                    }
                    if (!StringUtils.isEmpty(groupId)) {
                        bean.setGroupId(groupId);
                    }
                    if(StringUtils.isBlank(bean.getIsCombined())){
                        bean.setIsCombined(String.valueOf(CombineWeightEnum.IS_NOT_COMBINED.getValue()));
                    }
                    BeanUtils.copyProperties(form, bean);
                    List<String> msgList = validate(form);
                    Supplier supplier = convertBeanFromForm(form);
                    if (msgList == null || msgList.size() == 0) {
                        try {
                            supplier.setGroupId(Long.parseLong(groupId));
                            supplier.setState(StateEnum.Valid.getState());
                            supplier.setCreateUid(user.getId());
                            if (!supplierService.codeIsExist(supplier.getCode())) {
                                throw new BaseException(BaseConstants.ERR_SUPPLIER_CODE_EXIST);
                            }
                            supplierService.add(supplier);

                        } catch (BaseException e) {

                            errMsg.add(e.getErrorMsg());
                            errList.add(supplier);

                        } catch (Exception e) {

                            errMsg.add(e.getMessage());
                            errList.add(supplier);

                        }
                    } else {
                        StringBuffer msgStr = new StringBuffer();
                        for (String msg : msgList) {
                            msgStr.append(msg + "||");
                        }
                        msgStr.replace(msgStr.lastIndexOf("||"), msgStr.length(), "");
                        errMsg.add(msgStr.toString());
                        errList.add(supplier);
                    }
                }
                successNums = list.size() - errList.size();
                totalNums = list.size();
            }
        } catch (Exception e) {
            return getFailResult(BaseConstants.ERR_UNKOWN, e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(),e);
                }
            }
        }
        String fileKey = null;
        if (errList != null && errList.size() > 0) {
            String path = getRealPath("");
            File file = null;
            try {
                path += System.currentTimeMillis() + BaseConstants.DEFAULT_EXPORT_FILE_SUFFIX;
                file = new File(path);
                ExportBuilder builder = new ExportBuilder
                        (SupplierImportTemplateBean.class,
                                new SupplierParse()
                        );
                ExportFactory factory = ExportFactory.getExportFactory(
                        builder);
                factory.setErrMsgList(errMsg).setDataList(errList).outPut(file);
                fileKey = FileUtils.uploadFile("import/supplier/", file.getName(), file);
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            } finally {
                if (file != null) {
                    file.delete();
                }
            }
        }

        Map<String, String> returnMap = new HashMap<String, String>();
        returnMap.put("fileKey", fileKey);
        returnMap.put("successNums", String.valueOf(successNums));
        returnMap.put("totalNums", String.valueOf(totalNums));
        return getSuccessResult(returnMap);
    }

    private Supplier convertBeanFromForm(SupplierExportReq orgin) {
        Supplier supplier = new Supplier();
        try {
            BeanUtils.copyProperties(supplier, orgin);
        } catch (Exception e) {
            throw new BaseException(BaseConstants.ERR_COPYBEAN);
        }
        return supplier;
    }

}


